﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Login : System.Web.UI.Page
{
    DatabaseProcess dbClass = new DatabaseProcess();
    public DataTable dt;

    protected void Page_Load(object sender, EventArgs e)
    {
        //kiem tra trang thai khi redirect signup to login
        if (Request.QueryString["signup"] != null)
        {
            String status = Request.QueryString["signup"].ToString();
            if (status == "1")
            {
                signup_status.Text = "Sign Up Completed!";
            }
        }

        if (Session["username"] != null) {
            loginpage.Visible = false;
            notify.Text = "you are trying to log in while still logged in another account!! sign out first, please!";
        }
    }
  
    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        bool Authenticated = false;
        CheckBox chBox = (CheckBox)Login1.FindControl("RememberMe");
        Authenticated = UserAuthenticate(Login1.UserName, Login1.Password);
        e.Authenticated = Authenticated;
        if (Authenticated == true)
        {
            if (chBox.Checked == true)
            {
             //   to generate cookies
            }
            
            Response.Redirect("Home.aspx");
        }
    }

    private bool UserAuthenticate(string UserName, string Password)
    {
        bool boolReturnValue = false;
            dt = new DataTable();
            string chkUser = "Select * FROM [User_] where Email='" + UserName + "' AND Password_='" + Password + "'";
            dt = dbClass.ConnectDataBaseReturnDT(chkUser);
            if (dt.Rows.Count > 0)
            {
                boolReturnValue = true;
                Session["username"] = dt.Rows[0]["Email"].ToString();
                Session["ID"] = dt.Rows[0]["ID"];
                Session["role"] = dt.Rows[0]["role"].ToString();
                string updateLastLogin = "Update [User_] SET LastLogin='" + System.DateTime.Now.ToString() + "' where Id='" + Session["ID"].ToString() + "'";
                dbClass.ConnectDataBaseToInsert(updateLastLogin);
            }
            return boolReturnValue;
     }
    
}